package com.orangelife.mobile.discount.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.common.sp.UserSp;
import com.curry.android.http.HttpUtil;
import com.curry.android.net.NetworkUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.PhoneCallUtil;
import com.curry.android.util.TimeUtil;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.common.jump.CommonJumper;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.point.activity.MyPointActivity;
import com.orangelife.mobile.shop.activity.TraderDetailActivity;
import com.thirdsdk.umeng.UmShareBiz;
import com.orangelife.mobile.util.DateUtil;
import com.orangelife.mobile.util.FileHelper;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;
import com.orangelife.mobile.widget.SelectPicPopupWindowView;
import com.orangelife.mobile.web.WebWin;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.sso.UMSsoHandler;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 优惠详情
 *
 * @author yuyuxia
 */
@SuppressLint("HandlerLeak")
public class DetailActivity extends OrangeLifeBaseActivity {
    /** 弹出框 */
    SelectPicPopupWindowView menuWindow;
    /** 标题栏中的大标题，内容中的标题，发布时间，商家名称，商品描述内容，活动商家名称，活动时间，商家地址 */
    private TextView tvMenubarTitle, tvTitle, tvTime, tvSallor, tv_title_score,
            tvOne, tvActivitySallor, tvActivityTime, tvAddress;
    /** 分享按钮，打电话按钮 */
    private ImageButton ibShare, ibCall;
    /** 放图片的webview */
    private WebWin wwPhoto;
    private Map<String, Object> map = null;
    /** 接收详情数据 */
    private Map<String, Object> mapDetail;
    /** 地图 */
    private LinearLayout llMap;
    private Dialog dialog;
    /** 经度 */
    private float longitude;
    /** 纬度 */
    private float latitude;
    /** 用来储存通话记录的文件 */
    private String filename;

    private String actvtID;
    /** 积分的图标点击 */
    private LinearLayout llScore;
    /** -------------分享------------------------ */
    /** 首先在您的Activity中添加如下成员变量 */
    private final UMSocialService mController = UMServiceFactory
            .getUMSocialService("com.umeng.share");
    /** 分享title */
    private String uMtitle = "";
    /** 分享content */
    private String uMcontent = "";
    /** 商家图片 */
    UmShareBiz shareBiz;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discount_detail);
        shareBiz = new UmShareBiz(this);
        initeView();
        findView();
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(
                resultCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }


    /**
     * 初始化
     */
    private void initeView() {
        tvOne = (TextView) findViewById(R.id.tv_one);
        tv_title_score = (TextView) findViewById(R.id.tv_title_score);
        tvMenubarTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle = (TextView) findViewById(R.id.tv_good_title);
        tvTime = (TextView) findViewById(R.id.tv_time);
//		tvSallor = (TextView) findViewById(R.id.tv_name);
        tvActivitySallor = (TextView) findViewById(R.id.tv_seller_name);
        tvActivityTime = (TextView) findViewById(R.id.tv_activity_times);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        ibCall = (ImageButton) findViewById(R.id.ib_call);
        ibShare = (ImageButton) findViewById(R.id.ib_share);
        // ivPhoto = (ImageView) findViewById(R.id.ivPhoto);
        wwPhoto = (WebWin) findViewById(R.id.wwPhoto);
        llMap = (LinearLayout) findViewById(R.id.llMap);
        llScore = (LinearLayout) findViewById(R.id.ll_score);
        tv_title_score.setText(UserSp.getPoint());
    }

    /**
     * 赋值和设置监听器
     */
    @SuppressWarnings("unchecked")
    private void findView() {
        tvMenubarTitle.setText(getResources().getString(
                R.string.favorable_title));
        llScore.setVisibility(View.INVISIBLE);
        ibCall.setOnClickListener(listener);
        ibShare.setOnClickListener(listener);
        llMap.setOnClickListener(listener);
        tvActivitySallor.setOnClickListener(listener);
        llScore.setOnClickListener(listener);
        Intent intent = getIntent();
        map = (Map<String, Object>) intent.getSerializableExtra("detail");
        dialog = DialogHelper.getInstance().createLoadingDialog(this, Constant.LOADING);
        dialog.show();
        getDiscountDetail();
    }

    /** 设置详情 */
    private void setDetail() {
        uMtitle = mapDetail.get("actvtName").toString();/* 店铺名称 */
        uMcontent = mapDetail.get("summary").toString();/* 活动内容 */
        /* 商家的图片 */

        actvtID = mapDetail.get("actvtID").toString();
        tvTitle.setText(mapDetail.get("actvtName").toString());
        // image.download(mapDetail.get("coverBig").toString(), ivPhoto);
        DateUtil dateUtil = new DateUtil();
        String disTime = mapDetail.get("tsedit").toString();
        String time = dateUtil.tranStringForDate(disTime);
        tvTime.setText(time);
//		tvSallor.setText(mapDetail.get("merchantName").toString());
        tvActivitySallor.setText(mapDetail.get("merchantName").toString());
        String starTime = mapDetail.get("startTime").toString();
        String endTime = mapDetail.get("endTime").toString();
        String start = dateUtil.tranStringToDay(starTime);
        String end = dateUtil.tranStringToDay(endTime);
        tvActivityTime.setText(start + "-" + end);
        tvAddress.setText(mapDetail.get("stree").toString());
        String des = mapDetail.get("description").toString();
        latitude = Float.parseFloat(mapDetail.get("latitude").toString());
        longitude = Float.parseFloat(mapDetail.get("longitude").toString());
        wwPhoto.loadDescWithBaseURL(des);

    }

    /**
     * 设置监听器
     */
    private OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                /** 打电话 */
                case R.id.ib_call:
                    if (mapDetail == null) {
                        break;
                    }
                    String phone = mapDetail.get("contactPhone").toString();
                    String name = mapDetail.get("merchantName").toString();
                    String time = TimeUtil.timeStampToDate(String.valueOf(System
                            .currentTimeMillis()));
                    Map<String, String> map = new LinkedHashMap<String, String>();
                    map.put("name", name);
                    map.put("phone", phone);
                    map.put("time", time);
                    saveFile(map);

                    PhoneCallUtil.getInstances().PhoneCall(DetailActivity.this, phone);
                    break;
                /** 分享 */
                case R.id.ib_share:
                    shareBiz.share(uMtitle, uMcontent, Constant.ACTIVITY_URL, actvtID);
                    break;
                /** 地图 */
                case R.id.llMap:
                    CommonJumper.jumpToBaiduLocation(DetailActivity.this, longitude, latitude);
                    break;
                case R.id.tv_seller_name:
                    if (!NetworkUtil.isConnectedNet(DetailActivity.this)) {
                        Toast.makeText(
                                DetailActivity.this,
                                DetailActivity.this.getResources().getString(
                                        R.string.net_disconnected),
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Intent intent = new Intent();
                    intent.putExtra("merID", mapDetail.get("merID").toString());
                    intent.setClass(DetailActivity.this, TraderDetailActivity.class);
                    startActivity(intent);
                    break;

                case R.id.ll_score:
                    if (!NetworkUtil.isConnectedNet(DetailActivity.this)) {
                        Toast.makeText(
                                DetailActivity.this,
                                DetailActivity.this.getResources().getString(
                                        R.string.net_disconnected),
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                    intent = new Intent();
                    intent.setClass(DetailActivity.this, MyPointActivity.class);
                    startActivity(intent);
                    break;

                default:
                    break;
            }
        }
    };

    /**
     * 处理获得的数据
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {

        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 7:
                    DialogHelper.closeDialog(dialog);
                    mapDetail = new HashMap<String, Object>();
                    mapDetail = (Map<String, Object>) JSONHelper.jsonToMap(
                            msg.obj.toString()).get("entity");
                    setDetail();
                    break;
                case 500:
                    DialogHelper.closeDialog(dialog);
                    ToastHelper.getInstance()._toast(
                            msg.obj.toString());
                    break;
                case 1011:
                    isLogin(dialog);
                    break;
                case 1:
                /*
                 * "scoreResult": "0", "score": "15", "scoreExchange": "1",
				 * "sponit":"5"
				 */
                    Map<String, Object> map = (Map<String, Object>) JSONHelper
                            .jsonToMap(msg.obj.toString()).get("entity");
                    if (map != null) {
                        String scoreResult = map.get("scoreResult").toString();
                        String sponit = map.get("sponit").toString();
                        if (scoreResult.equals("0")) {
                            UserSp.setPoint(String.valueOf(map.get("score")));
                            if (!StringUtil.isBlank(UserSp.getLoginID())) {
                                ToastHelper.getInstance()._toast("恭喜您获得了" + sponit + "积分");
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }

    };

    /**
     * 获取详情数据
     */
    private void getDiscountDetail() {
        Map<String, Object> mapSubmit = new HashMap<String, Object>();
        if (map != null) {
            String actvtID = map.get("actvtID").toString();
            mapSubmit.put("{actvtID}", actvtID);
        } else {
            Intent intent = getIntent();
            String actvId = intent.getStringExtra("actvtID");
            if (actvId != null && !actvId.equals("")) {
                mapSubmit.put("{actvtID}", actvId);
            }
        }
        Map<String, Object> rootMap = new HashMap<String, Object>();
        rootMap.put("map", mapSubmit);
//		rootMap.put("url", Constant.URL_DISCOUNT_DETAIL);
        rootMap.put("wat", 7);
        new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
    }

    /**
     * 储存通话记录
     *
     * @param map
     */
    @SuppressWarnings({"static-access", "rawtypes"})
    private void saveFile(Map map) {
        filename = UserSp.getRegPhone();
        FileHelper file = new FileHelper(this, filename + ".txt");
        file.saveFile(map, this.MODE_APPEND);
    }
}
